/*
 * @Author: DUST
 * @Date: 2023-05-15 15:49:16
 * @LastEditors: DUST
 * @LastEditTime: 2023-11-24 16:30:29
 * @FilePath: \business-card-system\admin\src\router\index.ts
 * @Description:
 * undefined
 */
import { createRouter, createWebHashHistory, RouteRecordRaw }  from "vue-router";
import { MakeBaseRoute } from "./routeUtils";
import adminRoute from "./admin";
import browseRoute from "./browse";
import userStore from "@/store/user";
import routerStore from "@/store/router";

const routes: Array<RouteRecordRaw> = [
  {
    path:"/",
    name: "index",
    component: () => import("@/views/index.vue"),
    meta: {
      title: "首页",
      isNotNeedLogin: true
    },
    redirect: "/admin"
  },
  {
    path:"/login",
    name: "login",
    component: () => import("@/views/login.vue"),
    meta: {
      title: "登录",
      isNotNeedLogin: true
    }
  },
  {
    path:"/blankWaitting/:name",
    name: "blankWaitting",
    component: () => import("@/views/blankWaitting.vue"),
    meta: {
      title: "跳转确认",
      isNotNeedLogin: true
    }
  },
  {
    ...MakeBaseRoute(() => import("@/layout/adminLayout.vue"), "admin", "管理后台", "/admin", adminRoute)
  },
  {
    ...MakeBaseRoute(() => import("@/layout/indexLayout.vue"), "browse", "首页", "/browse", browseRoute)
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

/**
 * @description: 前置守卫监听跳转页面
 * @param {*} to：要去的页面
 * @param {*} from：跳转前的页面
 * @param {*} next：执行函数，所有逻辑走完之后必须调用，页面才能正常显示
 */
router.beforeEach((to, from, next) => {
  // document.title
  // console.log(to);
  if(to.meta?.title) document.title = String(to.meta.title);
  // 查看是否需要登录的页面
  if(to.meta?.isNotNeedLogin) {
    routerStore.setLastPath(from.fullPath);
    next()
  } else {
    // console.log("", userStore.userinfo);
    if(userStore.userinfo) next() 
    else router.replace("/login") ;
  }
})

export default router;
